import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mobile.dart';
import 'package:wallpaper/components/placeholder/appbar_base.dart';
import 'package:wallpaper/components/my_types.dart';
import 'package:wallpaper/pages/navbar/child/mobile_page.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({super.key});

  @override
  State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage>
    with AutomaticKeepAliveClientMixin {
  final List<TypesBase> categoryList = [];
  bool isLoading = true;
  Timer? loadTimer; // 虽然保留变量名，但实际用作延时器
  bool hasLoaded = false; // 标记是否已加载过数据

  Future<void> getCategory() async {
    // 如果已经加载过数据，则不再重复加载
    if (hasLoaded) return;

    try {
      Response res = await mobileCategory();
      if (res.data == null || res.data['msg'] != 'success' || !mounted) return;
      List data = res.data['res']['category'];
      setState(() {
        for (var it in data) {
          categoryList.add(
            TypesBase(
                name: it['rname'],
                page: MobilePage(
                  id: it['id'],
                ),
                bg: it['cover']),
          );
        }
        hasLoaded = true; // 标记数据已成功加载
      });
    } catch (e) {
      print(e);
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  //初始化
  @override
  void initState() {
    super.initState();
    // 使用Future.delayed实现300毫秒后执行一次请求
    loadTimer = Timer(const Duration(milliseconds: 250), () {
      getCategory();
    });
  }

  @override
  void dispose() {
    loadTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      appBar: AppbarBase(title: '分类'),
      body: isLoading
          ? SizedBox(
              width: double.infinity,
              height: MediaQuery.of(context).size.height,
              child: Center(
                child: CircularProgressIndicator(),
              ),
            )
          : MyTypes(
              wallpapges: categoryList,
              vertical: false,
              isScroll: true,
            ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
